package libcore.util;

import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import libcore.server.IgnoreStrategy;

/**
 * 数据解析工具类
 */

public class DataParseUtil {

  private static final String TAG = "DataParseUtil";

  /**
   * GSON转换类
   */
  public static final Gson mGson =
    new GsonBuilder().addSerializationExclusionStrategy(new IgnoreStrategy()).create();

  public static String toJson(Object object) {
    if (object == null) return null;
    return mGson.toJson(object);
  }

  /**
   * 将JSON字符串转化成对象
   */
  public static <T> T fromJson(String json, Class<T> cls) {
    try {
      return mGson.fromJson(json, cls);
    } catch (JsonSyntaxException e) {
      Log.e(TAG, e.toString());
    }
    return null;
  }

  /**
   * 将jsonArray字符串转化成对象集合
   */
  public static <T> List<T> fromJsonArray(String json, Class<T> clazz) {
    try {
      return mGson.fromJson(json, new ParameterizedTypeImpl(clazz));
    } catch (JsonSyntaxException e) {
      Log.e(TAG, e.toString());
    }
    return null;
  }

  private static class ParameterizedTypeImpl implements ParameterizedType {
    Class clazz;

    public ParameterizedTypeImpl(Class clz) {
      clazz = clz;
    }

    @Override
    public Type[] getActualTypeArguments() {
      return new Type[] { clazz };
    }

    @Override
    public Type getRawType() {
      return List.class;
    }

    @Override
    public Type getOwnerType() {
      return null;
    }
  }
}
